#include "itemdao.h"
#include <QDebug>
ItemDao::ItemDao(QString hostName,QString dbName,QString username,QString password,QString tableName)
{
    db=QSqlDatabase::addDatabase("QSQLITE");
    /*设置数据库的相关参数*/
    db.setHostName(hostName);
    db.setDatabaseName(dbName);
    db.setUserName(username);
    db.setPassword(password);
    if(db.open())//如果数据库成功打开
    {
        qDebug()<<"database succeeded to open";
    }
    else
    {
        qDebug()<<"database failed to open";
    }
    QSqlQuery query(db);//新建一个查询
    query.exec(QString("select count(*) from sqlite_master where type='table' and name='%1'").arg(tableName));
    if(query.next()&&query.value(0).toInt()!=0)//如果表已经存在
    {
        qDebug()<<"table is exist";//调试信息
    }
    else//否则
    {
        qDebug()<<"table is not exist";
        bool success=query.exec(QString("create table %1(content varchar,time varchar,is_finish int)").arg(tableName));
        if(success)
        {
            qDebug()<<"table is created successfully";
        }
        else
        {
            qDebug()<<"table is not created successfully";
        }
    }
    this->tableName=tableName;
}

int ItemDao::insertItem(QString content, QDateTime endTime)
{
    bool success;
    db=QSqlDatabase::database(QSqlDatabase::defaultConnection,true);
    QSqlQuery query(db);
    query.prepare(QString("insert into %1 values(?,?,?)").arg(tableName));
    query.bindValue(0,content);
    query.bindValue(1,endTime.toString("yyyy-MM-dd hh:mm:ss"));
    query.bindValue(2,0);
    qDebug()<<query.lastQuery();
    success=query.exec();
    if(success)
    {
        query.exec(QString("select max(rowid) from %1").arg(tableName));
        if(query.next())
            return query.value(0).toInt();
        return -1;
    }
    else
    {
        return -1;
    }
}

QList<ItemDao::ItemData> ItemDao::queryItem()
{
    QList<ItemData> itemdatas;
    db=QSqlDatabase::database(QSqlDatabase::defaultConnection,true);
    QSqlQuery query(db);
    query.exec(QString("select rowid,content,time from %1 where is_finish=0").arg(tableName));
    while(query.next())
    {
        ItemData item;
        item.id=query.value(0).toInt();
        item.content=query.value(1).toString();
        item.dateTime=query.value(2).toString();
        itemdatas.append(item);
    }
    return itemdatas;
}

bool ItemDao::finishItem(int id, int result)
{
    bool ok;
    db=QSqlDatabase::database(QSqlDatabase::defaultConnection,true);
    QSqlQuery query(db);
    ok=query.exec(QString("update %1 set is_finish=%2 where rowid=%3").arg(tableName).arg(result).arg(id));
    return ok;
}
